/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bittorentlike;

import define.Define;
import java.util.ArrayList;

/**
 *
 * @author Xuan Cau
 */
public class ThreadChunk extends Thread
{
    private ThreadDowload _main;
    private byte[] _sha;
    private byte[] _chunk;
    public int _id_chunk;
    public long _begin;
    private int _status;
    public final int PAUSE = 0;
    public final int DOWNLOAD = 1;
    public ThreadChunk(ThreadDowload main,byte[] sha,int id)
    {
        _main = main;
        _sha = sha;
        Send send = new Send();
        send.SendDownload(_sha);
        _id_chunk = id;
        _chunk = null;
        _begin = Util.Utils.Seconds();
        _status = DOWNLOAD;
    }
    public void run()
    {
        while(true)
        {
            if(_status == DOWNLOAD)
            {
                _chunk = _main.GetChunk(_sha);
                if(_chunk != null)
                {
                    // tinh toc do.
                    int time = (int)(Util.Utils.Seconds() - _begin);
                    if(time > 0)
                    {
                        float speed = (float)((Define.MAX_CHUNK/time)/1024);
                        _main.SetSpeed(speed);
                    }
                    else
                    {
                        float speed = (float)((Define.MAX_CHUNK)/1024);
                        _main.SetSpeed(speed);
                    }

                    _main.NewChunk(_chunk,_id_chunk);
                    _chunk = null;
                    _id_chunk = _main.GetIdChunk();
                    if(_id_chunk == -1)
                        break;
                    else
                    {
                        _sha = _main.GetTorrent(_id_chunk);
                        Send send = new Send();
                        send.SendDownload(_sha);
                        _begin = Util.Utils.Seconds();
                    }
                }
                else
                {
                    if(Util.Utils.Seconds() - _begin >= define.Define.TIME_MAX_WAIT)
                    {
                        Send send = new Send();
                        send.SendDownload(_sha);
                        _begin = Util.Utils.Seconds();
                    }
                }
            }
        }
    }
    public byte[] GetChunk()
    {
        return _chunk;
    }
    public void Pause()
    {
        if(_status == PAUSE)
        {
            _status = DOWNLOAD;
        }
        else
        {
            _status = PAUSE;
        }
    }
}
